using TerritoryGame.Application.Interfaces;
using TerritoryGame.Application.Commands;
using TerritoryGame.Application.Dtos;
using TerritoryGame.Domain.Interfaces;
using TerritoryGame.Domain.Entities.App;
using TerritoryGame.Domain.ValueObjects;
using TerritoryGame.Domain.DomainEvents;
using TerritoryGame.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;

namespace TerritoryGame.Application.Services;

/// <summary>
/// 头像服务实现
/// </summary>
public class AppAvatarService : IAppAvatarService
{
    private readonly TerritoryGameDbContext _db;
    private readonly IDomainEventPublisher _eventPublisher;
    private readonly string _avatarStoragePath;
    private readonly long _maxFileSize = 5 * 1024 * 1024; // 5MB
    private readonly string[] _allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };

    public AppAvatarService(
        TerritoryGameDbContext db,
        IDomainEventPublisher eventPublisher,
        IConfiguration configuration)
    {
        _db = db;
        _eventPublisher = eventPublisher;
        _avatarStoragePath = configuration["AvatarStorage:Path"] ?? "wwwroot/avatars";
        
        // 确保存储目录存在
        if (!Directory.Exists(_avatarStoragePath))
        {
            Directory.CreateDirectory(_avatarStoragePath);
        }
    }

    /// <summary>
    /// 获取用户头像信息
    /// </summary>
    public async Task<ApiResult> GetUserAvatarInfoAsync(Guid userId)
    {
        try
        {
            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");
            }

            // 检查用户是否有自定义头像
            var hasCustomAvatar = !string.IsNullOrEmpty(user.Avatar) && 
                                user.Avatar != "default-avatar.png" &&
                                !user.Avatar.Contains("default");

            var fileName = hasCustomAvatar ? user.Avatar : "default-avatar.png";
            var avatarUrl = $"/api/users/avatar-file/{fileName}";
            var filePath = hasCustomAvatar && !string.IsNullOrEmpty(user.Avatar) ? Path.Combine(_avatarStoragePath, user.Avatar) : null;

            // 获取文件信息
            long fileSize = 0;
            DateTime? uploadTime = null;
            string contentType = "image/png";

            if (hasCustomAvatar && filePath != null && File.Exists(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                fileSize = fileInfo.Length;
                uploadTime = fileInfo.CreationTimeUtc;
                contentType = GetContentTypeFromExtension(Path.GetExtension(fileName) ?? string.Empty);
            }

            var result = new
            {
                UserId = user.Id,
                Username = user.Username,
                AvatarUrl = avatarUrl,
                FileName = fileName,
                FileSize = fileSize,
                FileSizeFormatted = FormatFileSize(fileSize),
                ContentType = contentType,
                UploadTime = uploadTime,
                IsDefault = !hasCustomAvatar,
                HasCustomAvatar = hasCustomAvatar
            };

            return ApiResult.Success("获取用户头像信息成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取用户头像信息时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取用户头像信息时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 上传用户头像
    /// </summary>
    public async Task<ApiResult> UploadUserAvatarAsync(Guid userId, IFormFile file, Guid currentUserId)
    {
        try
        {
            // 验证文件
            var validationResult = ValidateAvatarFile(file);
            if (!validationResult.IsValid)
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, validationResult.ErrorMessage);
            }

            // 查找用户
            var user = await _db.Users
                .Where(u => !u.IsDeleted && u.Id == userId)
                .FirstOrDefaultAsync();

            if (user == null)
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "用户不存在");
            }

            // 保存旧头像信息用于删除
            var oldAvatarUrl = user.Avatar;
            var oldFileName = !string.IsNullOrEmpty(oldAvatarUrl) ? Path.GetFileName(oldAvatarUrl) : null;
            var oldFilePath = !string.IsNullOrEmpty(oldFileName) ? Path.Combine(_avatarStoragePath, oldFileName) : null;

            // 检查旧头像是否为默认头像，如果是则不允许删除
            var isOldAvatarDefault = !string.IsNullOrEmpty(oldFileName) && 
                                   (oldFileName.Contains("default-avatar") || oldFileName.Contains("default"));

            // 生成新文件名
            var fileExtension = Path.GetExtension(file.FileName);
            var newFileName = $"{userId}_{DateTime.UtcNow:yyyyMMddHHmmss}{fileExtension}";
            var newFilePath = Path.Combine(_avatarStoragePath, newFileName);

            // 读取文件二进制数据
            byte[] fileBytes;
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);
                fileBytes = memoryStream.ToArray();
            }

            // 保存文件到磁盘
            await File.WriteAllBytesAsync(newFilePath, fileBytes);

            // 更新用户头像URL
            user.Avatar = newFileName;
            user.UpdatedAt = DateTime.UtcNow;

            Console.WriteLine($"准备更新用户头像 - UserId: {userId}, OldAvatar: {oldAvatarUrl}, NewAvatar: {newFileName}");

            await _db.SaveChangesAsync();

            // 验证数据库更新是否成功
            var updatedUser = await _db.Users
                .Where(u => u.Id == userId)
                .Select(u => new { u.Avatar, u.UpdatedAt })
                .FirstOrDefaultAsync();

            if (updatedUser != null)
            {
                Console.WriteLine($"数据库更新成功 - UserId: {userId}, Avatar: {updatedUser.Avatar}, UpdatedAt: {updatedUser.UpdatedAt}");
            }
            else
            {
                Console.WriteLine($"警告：无法验证用户头像更新 - UserId: {userId}");
            }

            // 删除旧头像文件（如果不是默认头像）
            if (!string.IsNullOrEmpty(oldFilePath) && File.Exists(oldFilePath) && !isOldAvatarDefault)
            {
                try
                {
                    File.Delete(oldFilePath);
                    Console.WriteLine($"已删除旧头像文件: {oldFilePath}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"删除旧头像文件时发生错误: {ex.Message}");
                    // 不抛出异常，因为新头像已经上传成功
                }
            }

            var result = new
            {
                UserId = user.Id,
                Username = user.Username,
                AvatarUrl = newFileName,
                FileName = newFileName,
                FileSize = fileBytes.Length,
                FileSizeFormatted = FormatFileSize(fileBytes.Length),
                ContentType = file.ContentType,
                UploadTime = DateTime.UtcNow,
                OldAvatarDeleted = !isOldAvatarDefault && !string.IsNullOrEmpty(oldFilePath) && File.Exists(oldFilePath) == false,
                DatabaseUpdated = updatedUser?.Avatar == newFileName,
                OldAvatarUrl = oldAvatarUrl
            };

            return ApiResult.Success("头像上传成功", result);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"上传头像时发生错误: {ex.Message}");
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"上传头像时发生错误: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取头像文件
    /// </summary>
    public async Task<(byte[] FileBytes, string ContentType, string FileName)> GetAvatarFileAsync(string fileName)
    {
        try
        {
            // 检查是否为默认头像请求
            if (fileName.Contains("default-avatar") || fileName.Contains("default"))
            {
                var defaultAvatarPath = Path.Combine(_avatarStoragePath, "default-avatar.png");
                if (File.Exists(defaultAvatarPath))
                {
                    var defaultBytes = await File.ReadAllBytesAsync(defaultAvatarPath);
                    return (defaultBytes, "image/png", "default-avatar.png");
                }
                else
                {
                    // 创建默认头像文件
                    var defaultBytes = CreateDefaultAvatar();
                    await File.WriteAllBytesAsync(defaultAvatarPath, defaultBytes);
                    return (defaultBytes, "image/png", "default-avatar.png");
                }
            }

            // 处理自定义头像
            var filePath = Path.Combine(_avatarStoragePath, fileName);
            
            if (!File.Exists(filePath))
            {
                // 文件不存在，返回默认头像
                var defaultAvatarPath = Path.Combine(_avatarStoragePath, "default-avatar.png");
                if (File.Exists(defaultAvatarPath))
                {
                    var defaultBytes = await File.ReadAllBytesAsync(defaultAvatarPath);
                    return (defaultBytes, "image/png", "default-avatar.png");
                }
                else
                {
                    var defaultBytes = CreateDefaultAvatar();
                    await File.WriteAllBytesAsync(defaultAvatarPath, defaultBytes);
                    return (defaultBytes, "image/png", "default-avatar.png");
                }
            }

            // 读取文件二进制数据
            var fileBytes = await File.ReadAllBytesAsync(filePath);
            var contentType = GetContentTypeFromExtension(Path.GetExtension(fileName));
            
            return (fileBytes, contentType, fileName);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"获取头像文件时发生错误: {ex.Message}");
            // 返回默认头像
            var defaultBytes = CreateDefaultAvatar();
            return (defaultBytes, "image/png", "default-avatar.png");
        }
    }

    /// <summary>
    /// 验证头像文件
    /// </summary>
    private (bool IsValid, string ErrorMessage) ValidateAvatarFile(IFormFile file)
    {
        if (file == null || file.Length == 0)
        {
            return (false, "请选择要上传的文件");
        }

        if (file.Length > _maxFileSize)
        {
            return (false, $"文件大小不能超过 {FormatFileSize(_maxFileSize)}");
        }

        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (!_allowedExtensions.Contains(extension))
        {
            return (false, $"不支持的文件格式，支持的格式：{string.Join(", ", _allowedExtensions)}");
        }

        return (true, string.Empty);
    }

    /// <summary>
    /// 从URL获取头像信息
    /// </summary>
    private AvatarInfo GetAvatarInfoFromUrl(string avatarUrl)
    {
        var fileName = Path.GetFileName(avatarUrl);
        var filePath = Path.Combine(_avatarStoragePath, fileName);
        
        if (File.Exists(filePath))
        {
            var fileInfo = new FileInfo(filePath);
            return new AvatarInfo(
                avatarUrl,
                fileName,
                fileInfo.Length,
                GetContentTypeFromExtension(Path.GetExtension(fileName)),
                fileInfo.CreationTimeUtc
            );
        }

        return AvatarInfo.CreateDefault();
    }

    /// <summary>
    /// 格式化文件大小
    /// </summary>
    private string FormatFileSize(long bytes)
    {
        if (bytes < 1024)
            return $"{bytes} B";
        else if (bytes < 1024 * 1024)
            return $"{bytes / 1024.0:F1} KB";
        else
            return $"{bytes / (1024.0 * 1024.0):F1} MB";
    }

    /// <summary>
    /// 根据扩展名获取内容类型
    /// </summary>
    private string GetContentTypeFromExtension(string extension)
    {
        return extension.ToLowerInvariant() switch
        {
            ".jpg" or ".jpeg" => "image/jpeg",
            ".png" => "image/png",
            ".gif" => "image/gif",
            ".bmp" => "image/bmp",
            _ => "application/octet-stream"
        };
    }

    /// <summary>
    /// 创建默认头像（PNG格式）
    /// </summary>
    private byte[] CreateDefaultAvatar()
    {
        // 创建一个简单的PNG格式默认头像
        // 使用一个简单的1x1像素的PNG图像作为默认头像
        var pngData = new byte[] {
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG签名
            0x00, 0x00, 0x00, 0x0D, // IHDR长度
            0x49, 0x48, 0x44, 0x52, // "IHDR"
            0x00, 0x00, 0x00, 0x01, // 宽度1
            0x00, 0x00, 0x00, 0x01, // 高度1
            0x08, // 位深度
            0x02, // 颜色类型 (RGB)
            0x00, // 压缩方法
            0x00, // 过滤方法
            0x00, // 交错方法
            0x37, 0x6E, 0xF9, 0x24, // IHDR CRC
            0x00, 0x00, 0x00, 0x0C, // IDAT长度
            0x49, 0x44, 0x41, 0x54, // "IDAT"
            0x08, 0x99, 0x01, 0x01, // 压缩数据
            0x00, 0x00, 0x00, 0x00, // IDAT CRC
            0x00, 0x00, 0x00, 0x00, // IEND长度
            0x49, 0x45, 0x4E, 0x44, // "IEND"
            0xAE, 0x42, 0x60, 0x82  // IEND CRC
        };
        
        return pngData;
    }
} 